﻿using Dapper;
using System.Data.SqlClient;
using yunbo.Model.BI;

namespace yunbo.Repositorys.BIRepositorys
{
	public class PPRepository
	{
		public string data = "Data Source=121.37.93.71;Initial Catalog=FanXingMES;User Id=sa;Password=geili@2025;TrustServerCertificate=true;";

		/// <summary>
		/// 获取品牌
		/// </summary>
		/// <param name="state"></param>
		/// <param name="str"></param>
		/// <returns></returns>
		public List<PP> GetPP(int state, string? str)
		{
			List<PP> pp = new List<PP>();

			using (SqlConnection connection = new SqlConnection(data))
			{
				string sql = @"SELECT pp.pp_id,pp.pp_code,pp.pp_name,pp.pp_jc,pp.pp_ywmc,pp.pp_ks,pp.pp_state,pp.pp_isdelete,
(SELECT STRING_AGG(ks.ks_name, ',') FROM [dbo].[bd_ks] AS ks
     WHERE ks.ks_id IN (SELECT value FROM STRING_SPLIT(pp.pp_ks, ','))) AS pp_ks_name
FROM [dbo].[bd_pp] AS pp WHERE [pp_isdelete]=1 and [pp_state]=@state ";

				if (str != null)
				{
					sql += @" and ([pp_code] like @str or [pp_name] like @str or [pp_ywmc] like @str) ";
				}

				connection.Open();

				using (SqlCommand command = new SqlCommand(sql, connection))
				{
					command.Parameters.AddWithValue("@state", state);
					if (str != null)
					{
						command.Parameters.AddWithValue("@str", $"%{str}%");
					}

					using (SqlDataReader reader = command.ExecuteReader())
					{
						while (reader.Read())
						{
							pp.Add(new PP
							{
								pp_id = Convert.ToInt32(reader["pp_id"]),
								pp_code = reader["pp_code"].ToString(),
								pp_name = reader["pp_name"].ToString(),
								pp_jc = reader["pp_jc"].ToString(),
								pp_ywmc = reader["pp_ywmc"].ToString(),
								pp_ks = reader["pp_ks"].ToString(),
								pp_ks_name = reader["pp_ks_name"].ToString(),
								pp_state = Convert.ToInt32(reader["pp_state"])
							});
						}
					}
				}
			}
			return pp;
		}

		/// <summary>
		/// 绑定品牌下拉框
		/// </summary>
		/// <returns></returns>
		public List<PP> GetOnePP()
		{
			List<PP> pp = new List<PP>();

			using (SqlConnection connection = new SqlConnection(data))
			{
				string sql = @"select pp_id,pp_code,pp_name from bd_pp WHERE [pp_state]=1 and [pp_isdelete]=1";

				connection.Open();

				using (SqlCommand command = new SqlCommand(sql, connection))
				{
					using (SqlDataReader reader = command.ExecuteReader())
					{
						while (reader.Read())
						{
							pp.Add(new PP
							{
								pp_id = Convert.ToInt32(reader["pp_id"]),
								pp_code = reader["pp_code"].ToString(),
								pp_name = reader["pp_name"].ToString(),
							});
						}
					}
				}
			}
			return pp;
		}

		/// <summary>
		/// 改变状态
		/// </summary>
		/// <param name="id"></param>
		/// <param name="state"></param>
		/// <returns></returns>
		public bool StateChange(int id, int state)
		{
			try
			{
				using (SqlConnection connection = new SqlConnection(data))
				{
					string sql = @"update [dbo].[bd_pp] set [pp_state]=@State where [pp_id]=@Id";
					return connection.Execute(sql, new { Id = id, State = state }) > 0;
				}
			}
			catch (Exception ex)
			{
				// 记录日志等异常处理
				Console.WriteLine($"状态更改失败: {ex.Message}");
				return false;
			}
		}

		/// <summary>
		/// 新增
		/// </summary>
		/// <param name="pp"></param>
		/// <returns></returns>
		public bool AddPP(PP pp)
		{
			string sql = @"insert into [dbo].[bd_pp]
(pp_code, pp_name, pp_jc, pp_ywmc, pp_ks, pp_create_by)
values
(@code,@name,@jc,@ywmc,@ks,1)";

			try
			{
				using (SqlConnection connection = new SqlConnection(data))
				{
					connection.Open();
					using (SqlCommand command = new SqlCommand(sql, connection))
					{
						command.Parameters.AddWithValue("@code", pp.pp_code);
						command.Parameters.AddWithValue("@name", pp.pp_name);
						command.Parameters.AddWithValue("@jc", pp.pp_jc);
						command.Parameters.AddWithValue("@ywmc", pp.pp_ywmc);
						command.Parameters.AddWithValue("@ks", pp.pp_ks);

						int rowsAffected = command.ExecuteNonQuery();
						return rowsAffected > 0; // 如果插入成功，返回 true
					}
				}
			}
			catch (Exception ex)
			{
				// 记录日志或处理异常
				Console.WriteLine("An error occurred: " + ex.Message);
				return false; // 如果发生异常，返回 false
			}
		}

		/// <summary>
		/// 修改
		/// </summary>
		/// <param name="pp"></param>
		/// <returns></returns>
		public bool UpdatePP(PP pp)
		{
			string sql = @"update [dbo].[bd_pp] set
pp_name=@name, pp_jc=@jc, pp_ywmc=@ywmc, pp_ks=@ks,[pp_update_by]=1,[pp_update_time]=getdate()
where [pp_id]=@id";

			try
			{
				using (SqlConnection connection = new SqlConnection(data))
				{
					connection.Open();
					using (SqlCommand command = new SqlCommand(sql, connection))
					{
						command.Parameters.AddWithValue("@name", pp.pp_name);
						command.Parameters.AddWithValue("@jc", pp.pp_jc);
						command.Parameters.AddWithValue("@ywmc", pp.pp_ywmc);
						command.Parameters.AddWithValue("@ks", pp.pp_ks);
						command.Parameters.AddWithValue("@id", pp.pp_id);

						int rowsAffected = command.ExecuteNonQuery();
						return rowsAffected > 0; // 如果插入成功，返回 true
					}
				}
			}
			catch (Exception ex)
			{
				// 记录日志或处理异常
				Console.WriteLine("An error occurred: " + ex.Message);
				return false; // 如果发生异常，返回 false
			}
		}

		/// <summary>
		/// 删除
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public bool DelPP(int id)
		{
			try
			{
				using (SqlConnection connection = new SqlConnection(data))
				{
					string sql = @"UPDATE [dbo].[bd_pp] 
                       SET pp_isdelete = 0 
                       WHERE pp_id = @Id";

					return connection.Execute(sql, new { Id = id }) > 0;
				}
			}
			catch (Exception ex)
			{
				// 记录日志等异常处理
				Console.WriteLine($"删除失败: {ex.Message}");
				return false;
			}
		}

		/// <summary>
		/// 批量删除
		/// </summary>
		/// <param name="ids"></param>
		/// <returns></returns>
		public bool DelPPs(int[] ids)
		{
			// 参数验证
			if (ids == null || ids.Length == 0)
				return false;

			try
			{
				using (SqlConnection connection = new SqlConnection(data))
				{
					connection.Open();
					using (var transaction = connection.BeginTransaction()) // 添加事务
					{
						try
						{
							string sql = @"UPDATE [dbo].[bd_pp] 
		                                 SET pp_isdelete = 0 
		                                 WHERE pp_id IN @Ids";

							int affectedRows = connection.Execute(sql, new { Ids = ids }, transaction);
							transaction.Commit(); // 提交事务

							// 确保所有ID都成功更新
							return affectedRows == ids.Length;
						}
						catch
						{
							transaction.Rollback(); // 回滚事务
							throw;
						}
					}
				}
			}
			catch (Exception ex)
			{
				// 记录日志等异常处理
				Console.WriteLine($"批量删除失败: {ex.Message}");
				return false;
			}
		}

	}
}

